package cn.tedu._03vehicle.base.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUESTS_PER_MINUTE = 3;
    private static final int WINDOW_SIZE_SECONDS = 60;
    private final ConcurrentHashMap<String,Integer> clientCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastRequestTimes = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastRequest = lastRequestTimes.get(clientIp);
        log.debug("lastRequest:{}",lastRequest);
        if (lastRequest != null && lastRequest.plusSeconds(WINDOW_SIZE_SECONDS).isAfter(LocalDateTime.now())) {
            int count = clientCounts.getOrDefault(clientIp, 0);
            lastRequestTimes.put(clientIp, LocalDateTime.now());
            if (count >= MAX_REQUESTS_PER_MINUTE) {
//                response.setStatus(429);
//                return false;
                throw new RuntimeException("访问过于频繁");
            }
            clientCounts.put(clientIp, count + 1);
        } else {
            clientCounts.put(clientIp, 1);
            lastRequestTimes.put(clientIp, LocalDateTime.now());
        }
        return true;
//        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


}
